package com.dsunsoft.rtu.service.impl;

import com.dsunsoft.rtu.entity.Subject;
import com.dsunsoft.rtu.enums.SubjectType;
import com.dsunsoft.rtu.service.ToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

@Slf4j
@Service
public class ToolServiceImpl implements ToolService {

    @Override
    public List<Subject> pdfToExcel(MultipartFile file) {
        List<Subject> result = new ArrayList<>();
        if(file.isEmpty()){
            return result;
        }
        try {
            List<String> textList = readTextMultipartFile(file);
            result = parseTextList(textList);
        } catch (Exception e){
             log.error("读取文件出错"+e.getMessage());
        }
        return result;
    }

    public static void main(String[] args) {
        File file = new File("C:\\Users\\zb\\Desktop\\题目测试\\11--高处作业吊篮安拆考试题库.txt");
        List<String> textList = readText(file);
        List<Subject> subjectList = parseTextList(textList);
//        boolean bl1 = isAnswer("1.力相平衡（ACDE）");
//        boolean bl2 = isAnswer("23.力相平衡（A）");
//        boolean bl3 = isAnswer("45.力相平衡（√）");
//        boolean bl4 = isAnswer("123. 力相平衡（×）");
//        System.out.println(bl1);
//        System.out.println(bl2);
//        System.out.println(bl3);
//        System.out.println(bl4);
//
//        System.out.println(startsWithDigit("1.力相平衡（ACDE）"));
//        System.out.println(startsWithDigit("23.力相平衡（A）"));
//        System.out.println(startsWithDigit("123. 力相平衡（×）"));
//
//        List<String> answerList = getAnswerContents("力相平衡（ACDE）");
//        System.out.println(answerList.get(0));
//        List<String> subnumList = getSubjectNum("23.力相平衡（ACDE）");
//        System.out.println(subnumList.get(0));
//        List<String> subOptionList = getSubjectOption("A.力相平衡（ACDE）");
//        System.out.println(subOptionList.get(0));
//        List<String> subOptionList2 = getSubjectOption("B.力相平衡（ACDE）");
//        System.out.println(subOptionList2.get(0));
//        System.out.println(isSubOption("A.力相平衡（ACDE）"));
//        System.out.println(isSubOption("B力相平衡."));

         System.out.println(subjectList);


    }

    // 转换读取的文本
    public static List<Subject> parseTextList(List<String> textList){
        List<Subject> result = new ArrayList<>();
        // 当前题型
        String subType = "1";
        // 当前题号码
        Integer subTypeNum = 0;
        Subject subject= null;
        //当前是解析的是题干还是选项
        // 1 ：题干  2：选项
        String lineType = "1";
        // 上一行
        String preLine = "";
        // 上一个题干
        String preSubContent = "";
        // 上一个题目选项
        String preOptionContenet = "";
        // 是否开始题目行
        Boolean isStartSubject = false;
        for (int i =0;i<textList.size();i++){
            // 当前行
            String line = textList.get(i);
            // 下一行
            String nextLine = null;
            if(i < textList.size()-1){
                nextLine = textList.get(i+1);
            }
            // 空的忽略
            if(line == null || "".equals(line)){
                continue;
            }
            line = line.trim();
            //
            if(!isStartSubject && (startsWithChinesePrefix(line))){
                isStartSubject = true;
            }
            // 题目开始
            if(isStartSubject){
                // 判断题型
                if(startsWithChinesePrefix(line) && line.contains("单选题")){
                    subType = "1";
                    continue;
                }
                if(startsWithChinesePrefix(line) &&  line.contains("多选题")){
                    subType = "2";
                    continue;
                }
                if(startsWithChinesePrefix(line) &&  line.contains("判断题")){
                    subType = "2";
                    continue;
                }

                // 需要判断当前行是题干还是选项，还是换行接上一行的
                if(startsWithDigit(line)){
                    // 本行是题干开头
                    lineType = "1";
                    // 添加一道题
                    subject = new Subject();
                    subTypeNum +=1;
                    subject.setSubType(subType);
                    subject.setSubTypeName(SubjectType.getName(subType));
                    // 题干和答案在一行
                    String subjectNum = "";
                    String answer = "";
                    List<String> subjectNumList = getSubjectNum(line);
                    if(subjectNumList.size()>0){
                        subjectNum = subjectNumList.get(0);
                        System.out.println(subjectNum);
                    }
                    if(isAnswer(line)){
                        List<String> answerList = getAnswerContents(line);
                        if(answerList.size()>0){
                            answer = answerList.get(0);
                            System.out.println(answer);
                        }
                        subject.setSubAnswer(answer);
                        String lineSubContent = line.replace(answer,"")
                                .replace("(","")
                                .replace(")","")
                                .replace("（","")
                                .replace("）","")
                                .replace(subjectNum,"")
                                .replaceFirst(".","")
                                ;
                        System.out.println(lineSubContent);
                        subject.setSubContent(lineSubContent);
                        result.add(subject);
                        preSubContent = "";
                    }
                    else {
                        // 本行答案和题干不在一行
                        preSubContent =  line.replace(subjectNum,"")
                                .replaceFirst(".","");
                    }
                } else if(isSubOption(line)){
                    // 本行是选项开头
                    lineType = "2"; // 本行是选项
                    String optionType = "";// 选项
                    String optionContenet = "";
                    List<String> subjectOptionList = getSubjectOption(line);
                    if(subjectOptionList.size()>0){
                        optionType = subjectOptionList.get(0);
                        System.out.println(optionType);
                    }
                    optionContenet = line.replace(optionType,"")
                            .replaceFirst(".", "");
                    if(nextLine != null &&
                            (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))){
                        subject.getOptionList().add(optionContenet);
                        preOptionContenet = "";
                    } else {
                        preOptionContenet = optionContenet;
                    }
                }
                else {
                    // 含有结答案
                    if(isAnswer(line)){
                        String answer = "";
                        List<String> answerList = getAnswerContents(line);
                        if(answerList.size()>0){
                            answer = answerList.get(0);
                            System.out.println(answer);
                        }
                        subject.setSubAnswer(answer);
                        String lineSubContent = line.replace(answer,"")
                                .replace("(","")
                                .replace(")","")
                                .replace("（","")
                                .replace("）","");
                        System.out.println(lineSubContent);
                        preSubContent +=lineSubContent;
                        subject.setSubContent(preSubContent);
                        result.add(subject);
                        preSubContent = "";
                    } else {
                        if("1".equals(lineType)){
                            // 题干
                            preSubContent += line;
                        }
                        if("2".equals(lineType)){
                            // 题目选项
                            preOptionContenet += line;
                            if(nextLine != null &&
                                    (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))) {
                                subject.getOptionList().add(preOptionContenet);
                                preOptionContenet = "";
                            }
                        }
                    }
                }
                preLine = line;
            }
        }
        return  result;
    }

    public static boolean startsWithChinesePrefix(String str) {
        // 检查字符串是否为空或null
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 检查是否以“一”、“二”、“三”开头
        String[] prefixes = {"一", "二", "三", "四","五", "六", "七", "八", "九", "十"};
        for (String prefix : prefixes) {
            if (str.startsWith(prefix)) {
                return true;
            }
        }
        // 如果不是以这些中文字符开头，则返回false
        return false;
    }

    // 数字开头的为题干
    public static boolean startsWithDigit(String str) {
        // 检查字符串是否为空或null
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 检查第一个字符是否是数字
        boolean fisrtIsNum = Character.isDigit(str.charAt(0));
        return fisrtIsNum && isNumeric(str);
    }


    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        String regex = "^([0-9]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }

    public static List<String> getSubjectNum(String text) {
        List<String> contents = new ArrayList<>();
        String regex  = "^([0-9]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null && matcher.start() == 0) {
                contents.add(matcher.group(1));
            }
        }

        return contents;
    }

    public static boolean isSubOption(String str) {
        if (str == null) {
            return false;
        }
        String regex = "^([A-Z]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }

    public static List<String> getSubjectOption(String text) {
        List<String> contents = new ArrayList<>();
        String regex  = "^([A-Z]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null && matcher.start() == 0) {
                contents.add(matcher.group(1));
            }
        }

        return contents;
    }

    public static List<String> getAnswerContents(String text) {
        List<String> contents = new ArrayList<>();
        String regex = "\\（([^（）]*)\\）|\\(([^()]*)\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null) {
                // 匹配到的是中文圆括号内的内容
                contents.add(matcher.group(1));
            } else if (matcher.group(2) != null) {
                // 匹配到的是英文圆括号内的内容
                contents.add(matcher.group(2));
            }
        }

        return contents;
    }


    public static boolean isAnswer(String str) {
        if (str == null) {
            return false;
        }
            // 正则表达式，匹配中文圆括号“（）”或英文圆括号“()”
        String regex = "\\（([^（）]*)\\）|\\(([^()]*)\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }



    public static List<String>  readText(File file){
        List<String> textList = new ArrayList<>();
        try  {
            FileReader fileReader = new FileReader(file);
            BufferedReader br = new BufferedReader(fileReader);
            String line;
            while ((line = br.readLine()) != null) {
//                System.out.println(line);
                textList.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return textList;
    }

    public static List<String>  readTextMultipartFile(MultipartFile file){
        List<String> textList = new ArrayList<>();
        try  {
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
//                System.out.println(line);
                textList.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return textList;
    }
}
